const Base = require('./base.js');

module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.asset = this.model("system/asset");
		this.user_level = this.model("sys_user_level");
		this.user = this.model("system/user");
	}
	async indexAction() {
		if(this.isGet) {
			let levels = await this.user_level.select();

			console.log(levels);
			this.assign("userLevels", levels);
			return this.display();
		}

		let posts = this.post();
		let where = {};
		if(!think.isEmpty(posts.level)) {
			where.level = posts.level;
		}

		let fields = "id, score, amount, rebate, user_id, agency_id, create_time,level";
		const data = await this.asset.joinUserTable(posts, where, fields);
		return this.json(data);

	}

	async editAction() {
		if(this.isGet) {
			let id = this.get("id");
			let asset = await this.asset.findOne(id);
			let levels = await this.user_level.select();

			console.log(levels);
			this.assign("userLevels", levels);
			this.assign("asset", asset);
			return this.display();
		}

		let posts = this.post();

		let rows = await this.asset.transaction(async() => {
			let update = await this.asset.setOne(posts.id, {
				amount: posts.amount,
				score: posts.score,
				rebate: posts.rebate,
				level: posts.level

			});

			let userid = await this.asset.where({
				id: posts.id
			}).getField("user_id", true);
			await this.user.db(this.asset.db()).setOne(userid, {
				level: posts.level
			});

			return update;

		});

		if(rows == 0) {
			return this.fail("修改失败");
		}

		return this.success("修改成功");
	}

	async rechargeAction() {
		let posts = this.post();
		await this.asset.where({
			id: posts.id
		}).increment('amount', posts.amount);
		return this.success();

	}

};